package com.sky.handler;

import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理类
 * https://chat.deepseek.com/a/chat/s/c488ddc0-7429-4e3a-88da-638c7234ac4e
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * @param ex
     * @param request 它封装了 HTTP 请求的相关信息，Spring 会自动注入当前引发异常的请求信息。
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex, WebRequest request) {

        log.error("异常信息：{}", ex.getMessage());
        // 获取请求路径 uri=/api/users/123
//        String path = request.getDescription(false).replace("uri=", "");
//        // 获取查询参数
//        String queryString = request.getParameterMap().toString();
//        // 获取请求头等信息
//        String userAgent = request.getHeader("User-Agent");
//        log.error("请求异常路径：{},{},{}", path, queryString, userAgent);

        return Result.error(ex.getMessage());

    }


    /**
     * 处理SQL异常
     * 处理Spring数据完整性异常
     * Spring转换后的异常
     */
    @ExceptionHandler()
    public Result handleDataIntegrityViolation(DataIntegrityViolationException ex) {
        log.error("异常信息：{}", ex.getMessage());
        String message = "";
        // 可以根据具体原因提供更友好的错误信息
        Throwable rootCause = ex.getRootCause();
        if (rootCause != null) {
            message = rootCause.getMessage();
            if (message.contains("Duplicate entry")) {
                String[] split = message.split(" ");
                String username = split[2];
                message = username + MessageConstant.ALREADY_EXISTS;

            } else if (message.contains("foreign key constraint")) {
                message = "关联数据不存在";
            } else if (message.contains("cannot be null")) {
                message = "必填字段不能为空";
            } else {
                message = MessageConstant.UNKNOWN_ERROR;
            }
        }

        return Result.error(message);
    }

    /**
     * 处理SQL异常
     * 直接处理JDBC的原始异常（不推荐，通常让Spring转换即可）
     * SQLIntegrityConstraintViolationException是JDBC抛出的违反数据库完整性约束的异常，
     * 在Spring中通常被转换为DataIntegrityViolationException
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        //Duplicate entry 'zhangsan' for key 'employee.idx_username'
        log.error("异常信息：{}", ex.getMessage());
        String message = ex.getMessage();
        if (message.contains("Duplicate entry")) {
            String[] split = message.split(" ");
            String username = split[2];
            message = username + MessageConstant.ALREADY_EXISTS;
        } else if (message.contains("foreign key constraint")) {
            message = "关联数据不存在";
        } else if (message.contains("cannot be null")) {
            message = "必填字段不能为空";
        } else {
            message = MessageConstant.UNKNOWN_ERROR;
        }
        return Result.error(message);
    }


    /**

     *
     * @param ex
     * @return
     */
//    @ExceptionHandler
//    public Result exceptionHandler2(SQLIntegrityConstraintViolationException ex) {
//        log.error("异常信息：{}", ex.getMessage());
//        String message = ex.getMessage();
//        if (message.contains("Duplicate entry")) {
//            String[] split = message.split(" ");
//            String username = split[2];
//            String msg = username + MessageConstant.ALREADY_EXISTS;
//
//            return Result.error(msg);
//        }
//        return Result.error(MessageConstant.UNKNOWN_ERROR);
//
//    }

}
